import GameAI from '../ai/gameAI'

export default class AITest {
  constructor() {
    this.gameAI = new GameAI()
    this.testResults = []
  }

  /**
   * 运行所有测试
   */
  runAllTests() {
    console.log('开始AI测试...')
    
    this.testBasicFunctionality()
    this.testPerformance()
    this.testWinningMoves()
    this.testDefensiveMoves()
    this.testDifferentDifficulties()
    
    this.printResults()
  }

  /**
   * 测试基本功能
   */
  testBasicFunctionality() {
    console.log('测试基本功能...')
    
    // 测试空棋盘
    const emptyBoard = this.createEmptyBoard()
    const move = this.gameAI.getNextMove(emptyBoard, 1)
    
    if (move && move.row >= 0 && move.row < 15 && move.col >= 0 && move.col < 15) {
      this.addResult('基本功能', 'PASS', 'AI能够正确返回有效落子位置')
    } else {
      this.addResult('基本功能', 'FAIL', 'AI返回了无效的落子位置')
    }
  }

  /**
   * 测试性能
   */
  testPerformance() {
    console.log('测试性能...')
    
    const board = this.createTestBoard()
    const startTime = Date.now()
    
    this.gameAI.setDifficulty('hard')
    const move = this.gameAI.getNextMove(board, 1)
    
    const endTime = Date.now()
    const thinkingTime = endTime - startTime
    
    if (thinkingTime < 10000) { // 10秒内完成
      this.addResult('性能测试', 'PASS', `AI在${thinkingTime}ms内完成思考`)
    } else {
      this.addResult('性能测试', 'FAIL', `AI思考时间过长: ${thinkingTime}ms`)
    }
    
    // 测试性能监控
    const performanceReport = this.gameAI.getPerformanceReport()
    if (performanceReport.currentMove.thinkingTime) {
      this.addResult('性能监控', 'PASS', '性能监控功能正常')
    } else {
      this.addResult('性能监控', 'FAIL', '性能监控功能异常')
    }
  }

  /**
   * 测试必胜走法
   */
  testWinningMoves() {
    console.log('测试必胜走法...')
    
    // 创建一个有必胜机会的棋盘
    const board = this.createWinningBoard()
    const move = this.gameAI.getNextMove(board, 1)
    
    if (move) {
      // 模拟落子
      board[move.row][move.col] = 1
      
      // 检查是否获胜
      if (this.checkWin(board, move.row, move.col, 1)) {
        this.addResult('必胜走法', 'PASS', 'AI成功找到必胜走法')
      } else {
        this.addResult('必胜走法', 'FAIL', 'AI未能找到必胜走法')
      }
    } else {
      this.addResult('必胜走法', 'FAIL', 'AI未能返回有效走法')
    }
  }

  /**
   * 测试防守走法
   */
  testDefensiveMoves() {
    console.log('测试防守走法...')
    
    // 创建一个需要防守的棋盘
    const board = this.createDefensiveBoard()
    const move = this.gameAI.getNextMove(board, 1)
    
    if (move) {
      // 模拟落子
      board[move.row][move.col] = 1
      
      // 检查是否阻止了对手的连四
      const opponentMove = { row: 7, col: 7, player: 2 }
      board[opponentMove.row][opponentMove.col] = 2
      
      if (!this.checkWin(board, opponentMove.row, opponentMove.col, 2)) {
        this.addResult('防守走法', 'PASS', 'AI成功阻止了对手的威胁')
      } else {
        this.addResult('防守走法', 'FAIL', 'AI未能有效防守')
      }
    } else {
      this.addResult('防守走法', 'FAIL', 'AI未能返回有效走法')
    }
  }

  /**
   * 测试不同难度
   */
  testDifferentDifficulties() {
    console.log('测试不同难度...')
    
    const difficulties = ['easy', 'medium', 'hard']
    const board = this.createTestBoard()
    
    for (const difficulty of difficulties) {
      this.gameAI.setDifficulty(difficulty)
      const startTime = Date.now()
      
      const move = this.gameAI.getNextMove(board, 1)
      const thinkingTime = Date.now() - startTime
      
      if (move) {
        this.addResult(`${difficulty}难度`, 'PASS', `AI在${thinkingTime}ms内完成思考`)
      } else {
        this.addResult(`${difficulty}难度`, 'FAIL', 'AI未能返回有效走法')
      }
    }
  }

  /**
   * 创建空棋盘
   */
  createEmptyBoard() {
    const board = []
    for (let i = 0; i < 15; i++) {
      board[i] = []
      for (let j = 0; j < 15; j++) {
        board[i][j] = 0
      }
    }
    return board
  }

  /**
   * 创建测试棋盘
   */
  createTestBoard() {
    const board = this.createEmptyBoard()
    
    // 添加一些棋子
    board[7][7] = 1 // 中心黑子
    board[7][8] = 2 // 白子
    board[8][7] = 1 // 黑子
    board[8][8] = 2 // 白子
    
    return board
  }

  /**
   * 创建有必胜机会的棋盘
   */
  createWinningBoard() {
    const board = this.createEmptyBoard()
    
    // 创建一个连四的局面
    board[7][7] = 1
    board[7][8] = 1
    board[7][9] = 1
    board[7][10] = 1
    // 在(7,11)落子就能获胜
    
    return board
  }

  /**
   * 创建需要防守的棋盘
   */
  createDefensiveBoard() {
    const board = this.createEmptyBoard()
    
    // 创建一个对手即将连四的局面
    board[7][7] = 2
    board[7][8] = 2
    board[7][9] = 2
    board[7][10] = 2
    // 对手在(7,11)落子就能获胜，AI需要防守
    
    return board
  }

  /**
   * 检查是否获胜
   */
  checkWin(board, row, col, player) {
    const directions = [
      [1, 0],   // 水平
      [0, 1],   // 垂直
      [1, 1],   // 右下斜
      [1, -1]   // 右上斜
    ]

    for (let [dx, dy] of directions) {
      let count = 1
      
      // 正向检查
      for (let i = 1; i < 5; i++) {
        let newRow = row + dx * i
        let newCol = col + dy * i
        if (newRow < 0 || newRow >= 15 || newCol < 0 || newCol >= 15) break
        if (board[newRow][newCol] !== player) break
        count++
      }
      
      // 反向检查
      for (let i = 1; i < 5; i++) {
        let newRow = row - dx * i
        let newCol = col - dy * i
        if (newRow < 0 || newRow >= 15 || newCol < 0 || newCol >= 15) break
        if (board[newRow][newCol] !== player) break
        count++
      }
      
      if (count >= 5) return true
    }
    
    return false
  }

  /**
   * 添加测试结果
   */
  addResult(testName, status, message) {
    this.testResults.push({
      testName,
      status,
      message,
      timestamp: new Date().toISOString()
    })
  }

  /**
   * 打印测试结果
   */
  printResults() {
    console.log('\n=== AI测试结果 ===')
    
    let passed = 0
    let failed = 0
    
    for (const result of this.testResults) {
      const status = result.status === 'PASS' ? '✅' : '❌'
      console.log(`${status} ${result.testName}: ${result.message}`)
      
      if (result.status === 'PASS') {
        passed++
      } else {
        failed++
      }
    }
    
    console.log(`\n总计: ${passed}个通过, ${failed}个失败`)
    
    if (failed === 0) {
      console.log('🎉 所有测试通过！AI功能正常。')
    } else {
      console.log('⚠️ 部分测试失败，需要检查AI实现。')
    }
  }

  /**
   * 性能基准测试
   */
  benchmarkPerformance() {
    console.log('开始性能基准测试...')
    
    const board = this.createTestBoard()
    const iterations = 10
    const times = []
    
    for (let i = 0; i < iterations; i++) {
      const startTime = Date.now()
      this.gameAI.getNextMove(board, 1)
      const endTime = Date.now()
      times.push(endTime - startTime)
    }
    
    const avgTime = times.reduce((a, b) => a + b, 0) / times.length
    const minTime = Math.min(...times)
    const maxTime = Math.max(...times)
    
    console.log(`性能基准测试结果:`)
    console.log(`平均时间: ${avgTime.toFixed(2)}ms`)
    console.log(`最短时间: ${minTime}ms`)
    console.log(`最长时间: ${maxTime}ms`)
    
    return {
      average: avgTime,
      min: minTime,
      max: maxTime,
      times
    }
  }
} 